﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports ISNet.WebUI.WebTreeView
Imports log4net

Partial Class ShareMonthFormProject
    Inherits System.Web.UI.Page

    Public ScriptText As String = ""
    Dim lockhash As New Hashtable
    Dim cmmtcode As String = ""
    Dim basebud As String = ""
    Dim basecash As String = ""
    Dim basemode As Integer = 0
    Private Shared logger As ILog = LogManager.GetLogger("ShareMonthFormProject")

    Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
        WebCombo3.EncodeOutput = True
    End Sub
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        cmmtcode = Session("CMMT_OT_CODE")
        PlanYearsTxt.Text = Session("PlanYear")
        VersionTxt.Text = Session("Versions")
        If Session("FCTR") Is Nothing Then
            Response.Redirect("Selector.aspx?type=30")
        End If
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        
        If {"P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12"}.Contains(VersionTxt.Text) Then
            ImageButton4.Visible = True
            basemode = 1
        Else
            ImageButton4.Visible = False
        End If

        If {"C01", "C02", "C03", "C04", "C05", "C06", "C07", "C08", "C09", "C10", "C11", "C12"}.Contains(VersionTxt.Text) Then
            ImageButton5.Visible = True
            basemode = 2
        Else
            ImageButton5.Visible = False
        End If

        Try
            Dim adap As New DBdataTableAdapters.AppConfigsTableAdapter
            Dim dt As New DBdata.AppConfigsDataTable
            dt = adap.GetData
            For Each item As DBdata.AppConfigsRow In dt
                Select Case item.Name
                    Case "BASEBUDGET"
                        basebud = item.Value
                    Case "BASECASHFLOW"
                        basecash = item.Value
                End Select
            Next
        Catch ex As Exception
            logger.Error(ex.Message)

            logger.Error(ex.StackTrace)
        End Try


        If IsPostBack = False Then
            Session.Remove("Search")
            Session.Remove("search_fctr")
            Session.Add("Search", "true")
            Session("search_fctr") = ""
            'CheckExistData()
            'WebGrid1.ClearCachedDataSource()
            'WebGrid1.RebindDataSource()
        End If
        If IsPostBack = True Then
            GenerateValues()
        End If
        If IsPostBack = False Then

            Label1.Text = "ระบบจัดทำงบประมาณ >> จัดทำงบประมาณ >> การกระจายรายเดือน"
            'If Session("Versions") = 1 Then
            '    div1.Visible = False
            '    div2.Visible = False
            '    SearhBtn.Visible = False
            '    WebTreeView1.Visible = False
            '    WebTreeView2.Visible = False
            '    WebTreeView3.Visible = False
            'End If
            If VersionTxt.Text.Trim = "1" Or VersionTxt.Text.Trim = "2" Or VersionTxt.Text.Trim = "3" Or VersionTxt.Text.Trim = "4" Or VersionTxt.Text.Trim = "5" Then
                Dim adapter As New AttachmentTableAdapters.ProjectsTableAdapter
                Dim data As New Attachment.ProjectsDataTable
                'data = adapter.GetDataByPlanYear(Val(Session("PlanYear")))
                Dim sql = ""
                Dim prefil As String = ""
                prefil = Session("prefilter")
                sql += " WHERE 1 = 1 "
                sql += " AND planYear = " & PlanYearsTxt.Text & " "
                If prefil <> "" Then
                    sql += " AND FundCenter_FundCenterCode IN (" & prefil & ") "
                End If

                sql += " UNION  "
                sql += " SELECT ProjectCode, PlanYear, (Description) AS Description , CreatedDate, UpdatedDate, CreatedBy, UpdatedBy, FundCenter_FundCenterCode "
                sql += " FROM Projects AS Projects1 "
                sql += " WHERE Projects1.FundCenter_FundCenterCode IS NULL "
                sql += " AND Projects1.PlanYear = " & PlanYearsTxt.Text & " "

                adapter.GetDataByFilter(data, sql)

                ms8.DataValueField = "ProjectCode"
                ms8.DataTextField = "Description"
                ms8.DataSource = data
                ms8.DataBind()
                programs.Text = "โครงการ/งานสนับสนุน"
            Else
                Dim sql = "select * from fundedProgramProjects"
                Dim prefil As String = ""
                prefil = Session("prefilter")
                sql += " WHERE 1 = 1 "
                sql += " AND planYear = " & PlanYearsTxt.Text & " "
                If prefil <> "" Then
                    sql += " AND FundCenter_FundCenterCode IN (" & prefil & ") "
                End If
                Dim adapter As New SplitBudgetDSTableAdapters.FundedProgramProjectsTableAdapter
                Dim data As New SplitBudgetDS.FundedProgramProjectsDataTable
                adapter.GetDataByFilter(data, sql)
                ms8.DataValueField = "id"
                ms8.DataTextField = "FundedProgram"
                ms8.DataSource = data
                ms8.DataBind()
                programs.Text = "FundedProgram"
            End If

        End If
        If WebGrid1.IsFlyPostBack = False Then
            GenerateCommitment()
            GenerateActivity()
            'PlotNode()

        End If

        Dim prefil2 As String = ""
        prefil2 = Session("prefilter")
        Dim re_adap As New FormLockDSTableAdapters.FundCenterReleasesTableAdapter
        Dim rsql As String = ""
        rsql = " SELECT FundCenterReleases.FundCenter_FundCenterCode FROM FundCenterReleases "
        rsql += " WHERE PlanYear = " & Val(PlanYearsTxt.Text) & " "
        rsql += " AND Version = '" & VersionTxt.Text & "' "
        rsql += " AND FundCenter_FundCenterCode IN (" & prefil2 & ")" : rsql += " AND ReleaseFlag = 'Y' "
        'Response.Write(rsql)
        'Exit Sub
        Dim re_dt As New FormLockDS.FundCenterReleasesDataTable
        re_adap.GetDataByFilter(re_dt, rsql)
        For Each ritem As FormLockDS.FundCenterReleasesRow In re_dt
            lockhash.Remove(ritem.FundCenter_FundCenterCode) : lockhash.Add(ritem.FundCenter_FundCenterCode, True)
        Next
    End Sub
    Sub CheckExistData()
        Dim adapterx As New SplitData2TableAdapters.BudgetDetails1TableAdapter
        Dim datax As New SplitData2.BudgetDetails1DataTable
        Dim adapter12 As New SplitData2TableAdapters.Budget12TableAdapter
        Dim checksql = ""

        checksql += " SELECT Amount As SumAmount, FundCenter_FundCenterCode, Cmmt_CmmtCode, CmmtDetail_Id, Project_ProjectCode, ActivityType_ActivityTypeCode,Product_ProductCode, "
        checksql += " Activity_ActivityCode, FundedProgram, id , Project_FundCenterCode"
        checksql += "  FROM BudgetDetails"
        checksql += " Where 1=1 AND budgetdetails.PlanYear = " & Val(PlanYearsTxt.Text) & " "
        checksql += " AND budgetdetails.Version = '" & VersionTxt.Text & "'"
        Dim fctr As String = ""
        fctr = Session("search_fctr")
        Dim prefil As String = ""
        prefil = Session("prefilter")
        If fctr <> "" Then
            checksql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & fctr & ") "
        Else
            checksql += " AND BudgetDetails.FundCenter_FundCenterCode IN (" & prefil & ") "
        End If
        If hdf1.Value.ToString <> "" Then
            checksql += " AND BudgetDetails.Project_ProjectCode IN ("
            Dim Numx As Array = hdf1.Value.Split(",")
            For i = 0 To Numx.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx(i).ToString & "'"
            Next
            checksql += ") "
        End If

        If hdf3.Value.ToString <> "" Then
            checksql += " AND BudgetDetails.Cmmt_CmmtCode  IN ("
            Dim Numx2 As Array = hdf3.Value.Split(",")
            For i = 0 To Numx2.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx2(i).ToString & "'"
            Next
            checksql += ") "
        End If
        If hdf2.Value.ToString <> "" Then
            checksql += " AND  BudgetDetails.Activity_ActivityCode IN ("
            Dim Numx3 As Array = hdf2.Value.Split(",")
            For i = 0 To Numx3.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx3(i).ToString & "'"
            Next
            checksql += ") "
        End If

        adapterx.GetDataByFilter(datax, checksql)
        'Response.Write(checksql)
        'Exit Sub
        Dim counter As Decimal
        Dim FundCenter_FundCenterCode, Product_ProductCode, Cmmt_CmmtCode, Project_ProjectCode, ActivityType_ActivityTypeCode, Activity_ActivityCode, FundedProgram As String
        'Dim CmmtDetail_Id As String
        Dim project_fctr As String
        Dim countsql As String

        For Each row As SplitData2.BudgetDetails1Row In datax
            If lockhash(row.FundCenter_FundCenterCode) = True Then
                Continue For
            End If
            countsql = ""
            countsql += "        SELECT        COUNT(*) AS Expr1"
            countsql += " FROM Budget12"
            countsql += " WHERE 1=1 "
            'countsql += " AND (PlanYear = " & Val(PlanYearsTxt.Text) & ") AND (Version = '" & VersionTxt.Text & "') "
            countsql += " AND Budget12.BudgetDetail_Id = " & row.Id & " "
            FundCenter_FundCenterCode = row.FundCenter_FundCenterCode
            If row.IsCmmt_CmmtCodeNull = True Then
                Cmmt_CmmtCode = Nothing
            Else
                Cmmt_CmmtCode = row.Cmmt_CmmtCode
            End If
            'If row.IsCmmtDetail_IdNull = True Then
            '    CmmtDetail_Id = 0
            'Else
            '    CmmtDetail_Id = row.CmmtDetail_Id
            'End If

            If row.IsActivityType_ActivityTypeCodeNull = True Then
                ActivityType_ActivityTypeCode = Nothing
            Else
                ActivityType_ActivityTypeCode = row.ActivityType_ActivityTypeCode
            End If
            If row.IsActivity_ActivityCodeNull = True Then
                Activity_ActivityCode = Nothing
            Else
                Activity_ActivityCode = row.Activity_ActivityCode
            End If
            If row.IsProject_ProjectCodeNull = True Then
                Project_ProjectCode = Nothing
            Else
                Project_ProjectCode = row.Project_ProjectCode

            End If
            If row.IsFundedProgramNull = True Then
                FundedProgram = Nothing
            Else
                FundedProgram = row.FundedProgram

            End If
            If row.IsProduct_ProductCodeNull = True Then
                Product_ProductCode = Nothing
            Else
                Product_ProductCode = row.Product_ProductCode
            End If

            If row.IsProject_FundCenterCodeNull = True Then
                project_fctr = Nothing
            Else
                project_fctr = row.Project_FundCenterCode
            End If

            counter = adapterx.GetCountData(countsql)


            If counter = 0 Then
                If row.IsCmmtDetail_IdNull = True Then
                    adapter12.InsertQuery(Val(PlanYearsTxt.Text), Val(PlanYearsTxt.Text), VersionTxt.Text, Nothing, FundedProgram, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Nothing, Date.Now(), Nothing, Session("users"), Nothing, FundCenter_FundCenterCode, Val(PlanYearsTxt.Text), Nothing, Nothing, Cmmt_CmmtCode, Val(PlanYearsTxt.Text), Nothing, Val(PlanYearsTxt.Text), ActivityType_ActivityTypeCode, Activity_ActivityCode, Val(PlanYearsTxt.Text), Product_ProductCode, Val(PlanYearsTxt.Text), Project_ProjectCode, Val(PlanYearsTxt.Text), project_fctr, row.Id)
                Else
                    adapter12.InsertQuery(Val(PlanYearsTxt.Text), Val(PlanYearsTxt.Text), VersionTxt.Text, Nothing, FundedProgram, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Nothing, Date.Now(), Nothing, Session("users"), Nothing, FundCenter_FundCenterCode, Val(PlanYearsTxt.Text), Nothing, Nothing, Cmmt_CmmtCode, Val(PlanYearsTxt.Text), row.CmmtDetail_Id, Val(PlanYearsTxt.Text), ActivityType_ActivityTypeCode, Activity_ActivityCode, Val(PlanYearsTxt.Text), Product_ProductCode, Val(PlanYearsTxt.Text), Project_ProjectCode, Val(PlanYearsTxt.Text), project_fctr, row.Id)
                End If

            End If
            'MsgBox(counter)
            'MsgBox(countsql)
            'Exit Sub
        Next
        'Exit Sub
        Dim data2 As New SplitData2.Budget12DataTable

        checksql = "select *,0 As Amount from budget12 "
        checksql += " Where PlanYear = '" & Val(PlanYearsTxt.Text) & "' AND Version = '" & VersionTxt.Text & "' "

        fctr = Session("search_fctr")

        prefil = Session("prefilter")
        If fctr <> "" Then
            checksql += " AND Budget12.FundCenter_FundCenterCode IN (" & fctr & ") "
        Else
            checksql += " AND Budget12.FundCenter_FundCenterCode IN (" & prefil & ") "
        End If
        Dim counter2 As Decimal
        If hdf1.Value.ToString <> "" Then
            checksql += " AND Budget12.Project_ProjectCode IN ("
            Dim Numx As Array = hdf1.Value.Split(",")
            For i = 0 To Numx.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx(i).ToString & "'"
            Next
            checksql += ") "
        End If

        If hdf3.Value.ToString <> "" Then
            checksql += " AND Budget12.Cmmt_CmmtCode  IN ("
            Dim Numx2 As Array = hdf3.Value.Split(",")
            For i = 0 To Numx2.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx2(i).ToString & "'"
            Next
            checksql += ") "
        End If
        If hdf2.Value.ToString <> "" Then
            checksql += " AND  Budget12.Activity_ActivityCode IN ("
            Dim Numx3 As Array = hdf2.Value.Split(",")
            For i = 0 To Numx3.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx3(i).ToString & "'"
            Next
            checksql += ") "
        End If
        adapter12.GetDataByFilter(data2, checksql)
        Dim countsql2 As String
        For Each row As SplitData2.Budget12Row In data2
            If lockhash(row.FundCenter_FundCenterCode) = True Then
                Continue For
            End If
            countsql = ""
            countsql += "        SELECT        COUNT(*) AS Expr1"
            countsql += " FROM BudgetDetails"
            countsql += " WHERE 1=1   "
            'countsql += " AND (PlanYear = " & Val(PlanYearsTxt.Text) & ") AND (Version = '" & VersionTxt.Text & "') "

            countsql2 = ""
            countsql2 += "        SELECT        COUNT(*) As Expr1 "
            countsql2 += " FROM BudgetDetails"
            countsql2 += " WHERE 1=1   "
            countsql2 += " And Amount = 0 "
            'countsql += " AND (PlanYear = " & Val(PlanYearsTxt.Text) & ") AND (Version = '" & VersionTxt.Text & "') "

            countsql += " AND id = " & row.BudgetDetail_Id
            countsql2 += " AND id = " & row.BudgetDetail_Id
            counter = adapterx.GetCountData(countsql)
            counter2 = adapterx.GetCountData(countsql2)

            'Response.Write(countsql)
            'Response.Write(countsql2)
            'Exit Sub
            If counter = 0 Then
                adapter12.DeleteQuery(row.Id)
            End If
            If counter2 > 0 Then
                adapter12.DeleteQuery(row.Id)
            End If
        Next

    End Sub
    Sub GenerateCommitment()
        Dim adap As New BasicDataTableAdapters.CmmtsTableAdapter
        Dim dt As New BasicData.CmmtsDataTable
        dt = adap.GetData(Val(PlanYearsTxt.Text))
        ListBox1.DataSource = dt
        ListBox1.DataValueField = "CmmtCode"
        ListBox1.DataTextField = "Description"
        ListBox1.DataBind()
    End Sub
    Sub GenerateActivity()
        Dim adap As New BasicDataTableAdapters.ActivitiesTableAdapter

        Dim dt As New BasicData.ActivitiesDataTable

        dt = adap.GetDataByPlanYear(Val(PlanYearsTxt.Text))
        ListBox2.DataSource = dt
        ListBox2.DataValueField = "ActivityCode"
        ListBox2.DataTextField = "Description"
        ListBox2.DataBind()
    End Sub

    Protected Sub WebGrid1_InitializeColumn(sender As Object, e As ColumnEventArgs) Handles WebGrid1.InitializeColumn
        If e.Column.Name = "sumamount" Then
            e.Column.Caption = "รวม " & Val(PlanYearsTxt.Text)
        End If
        If e.Column.Caption = "Y+1" Or e.Column.Caption = "Y 1" Then
            e.Column.Caption = "ปี " & Val(PlanYearsTxt.Text) + 1
        End If
        If e.Column.Caption = "Y+2" Or e.Column.Caption = "Y 2" Then
            e.Column.Caption = "ปี " & Val(PlanYearsTxt.Text) + 2
        End If
        If e.Column.Caption = "Y+3" Or e.Column.Caption = "Y 3" Then
            e.Column.Caption = "ปี " & Val(PlanYearsTxt.Text) + 3
        End If
        If e.Column.Caption = "Y+4" Or e.Column.Caption = "Y 4" Then
            e.Column.Caption = "ปี " & Val(PlanYearsTxt.Text) + 4
        End If

        'If e.Column.ColumnType = ColumnType.CheckBox And lockhash.Count > 0 Then
        '    e.Column.IsRowChecker = False
        '    e.Column.Width = 24
        '    e.Column.Caption = " "
        'End If
    End Sub
    Protected Sub WebGrid1_InitializeDataSource(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        If IsPostBack = False Then
            Exit Sub
        End If
        'If IsPostBack = True Then
        Dim adapter12 As New SplitData2TableAdapters.Budget12TableAdapter
        'Dim data As New SplitData2.Budget12DataTable
        Dim data2 As New SplitData2.Budget12DataTable
        Dim checksql = ""
        Dim sessionsql = ""
        checksql = " select  Budget12.Id, Budget12.PlanYear, Budget12.BaseYear, Budget12.Version, Budget12.FunctionalArea, Budget12.FundedProgram, Budget12.Amount1, Budget12.Amount2, Budget12.Amount3, Budget12.Amount4, Budget12.Amount5, Budget12.Amount6, Budget12.Amount7, Budget12.Amount8, Budget12.Amount9, "
        sessionsql = " select  Budget12.Id, Budget12.PlanYear, Budget12.BaseYear, Budget12.Version, Budget12.FunctionalArea, Budget12.FundedProgram"

        sessionsql += " , ISNULL(((Budget12.[Amount1]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent1"
        sessionsql += " , ISNULL(((Budget12.[Amount2]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent2"
        sessionsql += " , ISNULL(((Budget12.[Amount3]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent3"
        sessionsql += " , ISNULL(((Budget12.[Amount4]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent4"
        sessionsql += " , ISNULL(((Budget12.[Amount5]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent5"
        sessionsql += " , ISNULL(((Budget12.[Amount6]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent6"
        sessionsql += " , ISNULL(((Budget12.[Amount7]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent7"
        sessionsql += " , ISNULL(((Budget12.[Amount8]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent8"
        sessionsql += " , ISNULL(((Budget12.[Amount9]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent9"
        sessionsql += " , ISNULL(((Budget12.[Amount10]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent10"
        sessionsql += " , ISNULL(((Budget12.[Amount11]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent11"
        sessionsql += " , ISNULL(((Budget12.[Amount12]* 100) / nullif([BudgetDetails].[Amount],0)),0) AS percent12"

        checksql += " Budget12.Amount10, Budget12.Amount11, Budget12.Amount12, Budget12.ForecastYear1, Budget12.ForecastYear2, Budget12.ForecastYear3, Budget12.ForecastYear4, Budget12.ProductItemNo, Budget12.CreatedDate, Budget12.UpdatedDate, Budget12.CreatedBy, Budget12.UpdatedBy, "
        sessionsql += " , Budget12.ForecastYear1, Budget12.ForecastYear2, Budget12.ForecastYear3, Budget12.ForecastYear4, Budget12.ProductItemNo, Budget12.CreatedDate, Budget12.UpdatedDate, Budget12.CreatedBy, Budget12.UpdatedBy, "
        checksql += " Budget12.FundCenter_FundCenterCode, Budget12.FundCenter_PlanYear, Budget12.Fund_FundCode, Budget12.Fund_PlanYear, Budget12.Cmmt_CmmtCode, Budget12.Cmmt_PlanYear, Budget12.CmmtDetail_Id, Budget12.ActivityType_PlanYear, "
        sessionsql += " Budget12.FundCenter_FundCenterCode, Budget12.FundCenter_PlanYear, Budget12.Fund_FundCode, Budget12.Fund_PlanYear, Budget12.Cmmt_CmmtCode, Budget12.Cmmt_PlanYear, Budget12.CmmtDetail_Id, Budget12.ActivityType_PlanYear, "
        checksql += "  ISNULL(CONVERT(VARCHAR(255),BudgetDetails.ActivityType_ActivityTypeCode), CONVERT(VARCHAR(255),(ISNULL(BudgetDetails.AssetNo,'') + ' ' + ISNULL(BudgetDetails.AssetDescription,'')))) AS ActivityType_ActivityTypeCode"
        sessionsql += "  ISNULL(CONVERT(VARCHAR(255),BudgetDetails.ActivityType_ActivityTypeCode), CONVERT(VARCHAR(255),(ISNULL(BudgetDetails.AssetNo,'') + ' ' + ISNULL(BudgetDetails.AssetDescription,'')))) AS ActivityType_ActivityTypeCode"
        checksql += " , Budget12.Activity_ActivityCode, Budget12.Activity_PlanYear, Budget12.Product_ProductCode, Budget12.Product_PlanYear, Budget12.Project_ProjectCode, Budget12.Project_PlanYear, "
        sessionsql += " , Budget12.Activity_ActivityCode, Budget12.Activity_PlanYear, Budget12.Product_ProductCode, Budget12.Product_PlanYear, Budget12.Project_ProjectCode, Budget12.Project_PlanYear, "
        checksql += " Budget12.Project_FundCenterCode, Budget12.BudgetDetail_Id, 0 AS Amount from budget12  LEFT JOIN BudgetDetails ON Budget12.BudgetDetail_Id = BudgetDetails.Id "
        sessionsql += " Budget12.Project_FundCenterCode, Budget12.BudgetDetail_Id, 0 AS Amount from budget12  LEFT JOIN BudgetDetails ON Budget12.BudgetDetail_Id = BudgetDetails.Id "
        checksql += " Where Budget12.PlanYear = '" & Val(PlanYearsTxt.Text) & "' AND Budget12.Version = '" & VersionTxt.Text & "' "
        sessionsql += " Where Budget12.PlanYear = '" & Val(PlanYearsTxt.Text) & "'"
        If basemode = 1 Then
            sessionsql += " AND Budget12.Version = '" & basebud & "' "
        ElseIf basemode = 2 Then
            sessionsql += " AND Budget12.Version = '" & basecash & "' "
        End If

        Dim fctr As String = ""
        fctr = Session("search_fctr")
        Dim prefil As String = ""
        prefil = Session("prefilter")
        If fctr <> "" Then
            checksql += " AND Budget12.FundCenter_FundCenterCode IN (" & fctr & ") "
            'sessionsql += " AND Budget12.FundCenter_FundCenterCode IN (" & fctr & ") "
        Else
            checksql += " AND Budget12.FundCenter_FundCenterCode IN (" & prefil & ") "
            'sessionsql += " AND Budget12.FundCenter_FundCenterCode IN (" & prefil & ") "
        End If
        If hdf1.Value.ToString <> "" Then
            checksql += " AND Budget12.Project_ProjectCode IN ("
            'sessionsql += " AND Budget12.Project_ProjectCode IN ("
            Dim Numx As Array = hdf1.Value.Split(",")
            For i = 0 To Numx.Length - 1
                If i <> 0 Then
                    checksql += ","
                    'sessionsql += ","
                End If
                checksql += "'" & Numx(i).ToString & "'"
                'sessionsql += "'" & Numx(i).ToString & "'"
            Next
            checksql += ") "
            'sessionsql += ") "
        End If

        If hdf3.Value.ToString <> "" Then
            checksql += " AND Budget12.Cmmt_CmmtCode  IN ("
            'sessionsql += " AND Budget12.Cmmt_CmmtCode  IN ("
            Dim Numx2 As Array = hdf3.Value.Split(",")
            For i = 0 To Numx2.Length - 1
                If i <> 0 Then
                    checksql += ","
                    'sessionsql += ","
                End If
                checksql += "'" & Numx2(i).ToString & "'"
                'sessionsql += "'" & Numx2(i).ToString & "'"
            Next
            checksql += ") "
            'sessionsql += ") "
        End If
        If hdf2.Value.ToString <> "" Then
            checksql += " AND  Budget12.Activity_ActivityCode IN ("
            'sessionsql += " AND  Budget12.Activity_ActivityCode IN ("
            Dim Numx3 As Array = hdf2.Value.Split(",")
            For i = 0 To Numx3.Length - 1
                If i <> 0 Then
                    checksql += ","
                    'sessionsql += ","
                End If
                checksql += "'" & Numx3(i).ToString & "'"
                'sessionsql += "'" & Numx3(i).ToString & "'"
            Next
            checksql += ") "
            'sessionsql += ") "
        End If
        checksql += " And (Select amount from budgetdetails where id = budget12.budgetdetail_Id) > 0 "
        'sessionsql += " And (Select amount from budgetdetails where id = budget12.budgetdetail_Id) > 0 "
        checksql += " Order By FundCenter_FundCenterCode "
        'sessionsql += " Order By FundCenter_FundCenterCode "

        adapter12.GetDataByFilter(data2, checksql)
        e.DataSource = data2
        data2.Columns("Amount").ReadOnly = False
        'Response.Write(checksql)
        'End If
        Session("basesql") = sessionsql
    End Sub

    Protected Sub WebGrid1_InitializeRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)
        ' Dim area_level As Decimal = Val(e.Row.Cells.GetNamedItem("area_level").Text)
        'If area_level = 9 Then
        'e.Row.Style.BackColor = Drawing.Color.Coral
        ' End If

        If e.Row.Type = RowType.Record Then
            Dim adapterdata As New SplitData2TableAdapters.BudgetDetailsTableAdapter
            Dim adapterx As New SplitData2TableAdapters.BudgetDetails1TableAdapter
            Dim pitemAdapter As New SplitData2TableAdapters.ProductItemsTableAdapter

            Dim dr As DataRow = e.Row.GetDataRow
            Dim FundCenter_FundCenterCode, Product_ProductCode, CmmtDetail_id, Cmmt_CmmtCode, Project_ProjectCode, ActivityType_ActivityTypeCode, Activity_ActivityCode, FundedProgram As String
            Dim project_fctr As String
            FundCenter_FundCenterCode = e.Row.Cells(1).Value


            If IsDBNull(e.Row.Cells(2).Value) = False Then
                Project_ProjectCode = e.Row.Cells(2).Value
            Else
                Project_ProjectCode = ""
            End If

            If IsDBNull(e.Row.DataRow("Project_FundCenterCode")) = False Then
                project_fctr = e.Row.DataRow("Project_FundCenterCode")
            Else
                project_fctr = ""
            End If

            If IsDBNull(e.Row.Cells(3).Value) = False Then
                Cmmt_CmmtCode = e.Row.Cells(3).Value
            Else
                Cmmt_CmmtCode = ""
            End If
                If IsDBNull(e.Row.Cells(4).Value) = False Then
                    Product_ProductCode = e.Row.Cells(4).Value
                Else
                    Product_ProductCode = ""
                End If
                If IsDBNull(e.Row.Cells(5).Value) = False Then
                    ActivityType_ActivityTypeCode = e.Row.Cells(5).Value
                Else
                    ActivityType_ActivityTypeCode = ""
                End If
                If IsDBNull(e.Row.Cells(6).Value) = False Then
                    If e.Row.Cells(6).Value <> 0 Then

                        CmmtDetail_id = e.Row.Cells(6).Value
                    Else
                        CmmtDetail_id = 0
                    End If
                Else
                    CmmtDetail_id = 0
                End If
                If IsDBNull(e.Row.Cells(7).Value) = False Then
                    Activity_ActivityCode = e.Row.Cells(7).Value
                Else
                    Activity_ActivityCode = ""
                End If
                'If e.Row.Cells(2).Value Is Nothing Then
                '    Project_ProjectCode = ""
                'Else
                '    Project_ProjectCode = e.Row.Cells(2).Value
                'End If
                'Try
                '    If e.Row.Cells(4).Value Is Nothing Then

                '        Product_ProductCode = ""
                '    Else

                '        Product_ProductCode = e.Row.Cells(4).Value
                '    End If
                'Catch ex As Exception
                '    Response.Write(Product_ProductCode)
                'End Try
                'Try
                '    If e.Row.Cells(5).Value Is Nothing Then
                '        ActivityType_ActivityTypeCode = ""
                '    Else
                '        ActivityType_ActivityTypeCode = e.Row.Cells(5).Value
                '    End If
                'Catch ex As Exception
                '    Response.Write(ActivityType_ActivityTypeCode)
                'End Try
                'Try
                '    If e.Row.Cells(6).Value Is Nothing Then
                '        CmmtDetail_id = ""
                '    Else
                '        CmmtDetail_id = e.Row.Cells(6).Value
                '    End If
                'Catch ex As Exception

                'End Try


                'If e.Row.Cells(7).Value Is Nothing Then
                '    Activity_ActivityCode = ""
                'Else
                '    Activity_ActivityCode = e.Row.Cells(7).Value
                'End If

                Dim dataX As New SplitData2.BudgetDetailsDataTable
                Dim mysql As String = ""
                mysql += "Select FormId,ProductItemNo From Budgetdetails where ID = " & dr("Budgetdetail_Id")

                adapterdata.GetDataByFilter(dataX, mysql)
            Dim fidtext
                Dim itemno
                For Each rowfid As SplitData2.BudgetDetailsRow In dataX
                If Not IsDBNull(rowfid.FormId) Then
                    fidtext = rowfid.FormId
                End If

                If rowfid.IsProductItemNoNull Then
                    itemno = 0
                Else
                    itemno = rowfid.ProductItemNo
                End If
            Next

            e.Row.Cells(1).Text = adapterdata.GetFundCenterName(FundCenter_FundCenterCode, Val(PlanYearsTxt.Text))
            If Project_ProjectCode <> "" Then
                If project_fctr <> "" Then
                    e.Row.Cells(2).Text = adapterdata.GetProjectFCTRName(Project_ProjectCode, Val(PlanYearsTxt.Text), project_fctr)
                Else
                    e.Row.Cells(2).Text = adapterdata.GetProjectNames(Project_ProjectCode, Val(PlanYearsTxt.Text))
                End If

            End If
                If Cmmt_CmmtCode <> "" Then

                    e.Row.Cells(3).Text = adapterdata.GetCmmtCode(Cmmt_CmmtCode, Val(PlanYearsTxt.Text))

                Else

                End If
                If Product_ProductCode <> "" Then
                    e.Row.Cells(4).Text = adapterdata.GetProductNames(Product_ProductCode, Val(PlanYearsTxt.Text))
                End If
                If ActivityType_ActivityTypeCode <> "" Then
                    If Left(e.Row.Cells(5).Value, 1) = "9" Then
                        e.Row.Cells(5).Text = e.Row.Cells(5).Value
                    Else
                        e.Row.Cells(5).Text = adapterdata.GetActTypeName(ActivityType_ActivityTypeCode, Val(PlanYearsTxt.Text))
                    End If
                End If
                If CmmtDetail_id <> 0 Then
                    e.Row.Cells(6).Text = adapterdata.GetCmmtDetails(CmmtDetail_id, Val(PlanYearsTxt.Text)) & " " & pitemAdapter.GetDesc(itemno, fidtext)
                Else
                    e.Row.Cells(6).Text = " " & " " & pitemAdapter.GetDesc(itemno, fidtext)
                End If

                If Activity_ActivityCode <> "" Then
                    e.Row.Cells(7).Text = adapterdata.GetActivityName(Activity_ActivityCode, Val(PlanYearsTxt.Text))
                End If


                Dim countsql As String
                countsql = ""
                countsql += " SELECT Amount As SumAmount"
                countsql += " FROM BudgetDetails"
                countsql += " Where id = " & dr("BudgetDetail_Id")
                'countsql += " WHERE 1=1  AND (PlanYear = '" & Val(PlanYearsTxt.Text) & "') AND (Version = '" & VersionTxt.Text & "') "

                'If Cmmt_CmmtCode = "" Then

                '    countsql += " And Cmmt_CmmtCode is null "
                'Else

                '    countsql += " And Cmmt_CmmtCode = '" & Cmmt_CmmtCode & "' "
                'End If
                'If CmmtDetail_id = 0 Then

                '    countsql += " And CmmtDetail_Id is null "
                'Else

                '    countsql += " And CmmtDetail_id = " & CmmtDetail_id & " "
                'End If

                'If ActivityType_ActivityTypeCode = "" Then

                '    countsql += " And ActivityType_ActivityTypeCode is null "
                'Else

                '    countsql += " And ActivityType_ActivityTypeCode = '" & ActivityType_ActivityTypeCode & "' "
                'End If
                'If Activity_ActivityCode = "" Then

                '    countsql += " And Activity_ActivityCode is null "
                'Else

                '    countsql += " And Activity_ActivityCode = '" & Activity_ActivityCode & "' "
                'End If
                'If Project_ProjectCode = "" Then


                '    If Val(Left(VersionTxt.Text, 1)) < 5 Then
                '        countsql += " And Project_ProjectCode is null "
                '    End If

                'Else

                '    If Val(Left(VersionTxt.Text, 1)) < 5 Then
                '        countsql += " And Project_ProjectCode = '" & Project_ProjectCode & "' "
                '    End If

                'End If
                'If FundedProgram = "" Then
                '    If Val(Left(VersionTxt.Text, 1)) < 5 Then

                '    Else
                '        countsql += " And FundedProgram is null "
                '    End If

                'Else
                '    If Val(Left(VersionTxt.Text, 1)) < 5 Then

                '    Else
                '        countsql += " And FundedProgram = '" & FundedProgram & "' "
                '    End If


                'End If
                'If Product_ProductCode = "" Then
                '    countsql += " And Product_ProductCode is null "
                'Else

                '    countsql += " And Product_ProductCode = '" & Product_ProductCode & "' "
                'End If
                'countsql += " AND (FundCenter_FundCenterCode = '" & FundCenter_FundCenterCode & "')"

                Dim counter2 = adapterx.GetAmountData(countsql)
                ' Response.Write(countsql)
                '     Response.Write(counter2)

                'If counter2 = 0 Then
                '    e.Row.Visible = False
                'End If

                e.Row.Cells(8).Value = counter2

                dr("Amount") = counter2

                e.Row.Cells.GetNamedItem("sumamount").Value = counter2
                e.Row.Cells.GetNamedItem("sumamount").Text = Format(counter2.ToString, "#,##0.00")
                Dim SumAMount As Decimal = Val(e.Row.Cells.GetNamedItem("sumamount").Value)

                Dim DiffSum As Decimal = Val(Val(e.Row.Cells(9).Value) + Val(e.Row.Cells(10).Value) + Val(e.Row.Cells(11).Value) + Val(e.Row.Cells(12).Value) + Val(e.Row.Cells(13).Value) + Val(e.Row.Cells(14).Value) + Val(e.Row.Cells(15).Value) + Val(e.Row.Cells(16).Value) + Val(e.Row.Cells(17).Value) + Val(e.Row.Cells(18).Value) + Val(e.Row.Cells(19).Value) + Val(e.Row.Cells(20).Value))
                If SumAMount <> DiffSum Then
                    e.Row.Cells(20).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(9).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(10).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(11).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(12).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(13).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(14).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(15).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(16).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(17).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(18).Style.BackColor = Drawing.Color.Coral
                    e.Row.Cells(19).Style.BackColor = Drawing.Color.Coral


                End If
                e.Row.Cells(1).ForceNoEdit = True
                e.Row.Cells(2).ForceNoEdit = True
                e.Row.Cells(3).ForceNoEdit = True
                e.Row.Cells(4).ForceNoEdit = True
                e.Row.Cells(5).ForceNoEdit = True
                e.Row.Cells(6).ForceNoEdit = True
                e.Row.Cells(7).ForceNoEdit = True
                e.Row.Cells(8).ForceNoEdit = True
            End If

        If e.Row.Type = RowType.Record Then
            If lockhash(e.Row.Cells(1).Value.ToString.Trim) = True Then
                'e.Row.Cells(0).Column.IsRowChecker = False
                e.Row.ForceNoEdit = True
                e.Row.Style.BackColor = Drawing.Color.Gray
            Else
                e.Row.Cells(0).Column.IsRowChecker = True
            End If

        End If
    End Sub





    Protected Sub WebGrid1_UpdateRow(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.RowEventArgs)

        Dim id As Decimal
        id = e.Row.KeyValue

        'WebGrid1.ClientAction.Alert(id)
        'Dim adapter2 As New BasicDataTableAdapters.CmmtDetailsTableAdapter
        'Dim cmmt_id As Decimal = adapter2.GetCmmtId(Val(e.Row.Cells(2).Value))
        Dim adapter As New SplitBudgetDSTableAdapters.Budget12TableAdapter
        ' adapter.UpdateOTProject(Val(e.Row.Cells(4).Value), Val(e.Row.Cells(5).Value), e.Row.Cells(6).Value, e.Row.Cells(7).Value, e.Row.Cells(8).Value, e.Row.Cells(9).Value, Date.Now, Session("users"), e.Row.Cells(1).Value, e.Row.Cells(3).Value, cmmtcode, e.Row.Cells(2).Value, id)
        adapter.UpdateBudget12(Val(e.Row.Cells(9).Value), Val(e.Row.Cells(10).Value), Val(e.Row.Cells(11).Value), Val(e.Row.Cells(12).Value), Val(e.Row.Cells(13).Value), Val(e.Row.Cells(14).Value), Val(e.Row.Cells(15).Value), Val(e.Row.Cells(16).Value), Val(e.Row.Cells(17).Value), Val(e.Row.Cells(18).Value), Val(e.Row.Cells(19).Value), Val(e.Row.Cells(20).Value), Val(e.Row.Cells(21).Value), Val(e.Row.Cells(22).Value), Val(e.Row.Cells(23).Value), Val(e.Row.Cells(24).Value), Now(), Session("users"), Val(id))


    End Sub

    Sub PlotNode()

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()

        Dim adapter As New FundCenterParentTableAdapters.fctr_viewTableAdapter
        Dim dt As New FundCenterParent.fctr_viewDataTable
        dt = adapter.GetDataByUser(Session("users"), Val(PlanYearsTxt.Text))

        Dim root_id As String

        MyNode.Text = "GSB"
        MyNode.Value = "0"
        root_id = "0"

        If dt.Count > 0 Then

            WebTreeView3.Nodes.Add(MyNode)

            Dim rootpath = ""
            Dim prefil As String = ""
            prefil = Session("prefilter")
            rootpath = FctrClass.GetRootPrefil(Session("users"), Val(Session("planyear")), prefil)
            Dim rootarr() As String = Split(rootpath, ",")
            WebTreeView3.Nodes.Add(MyNode)

            For i = 0 To rootarr.Length - 1
                PlotChild(rootarr(i), MyNode, 1)
            Next
        End If

    End Sub

    Sub PlotChild(ByVal gpath As String, ByRef cnode As WebTreeViewNode, ByVal level As Decimal)
        'Response.Write(gpath & "<br>")
        Dim Hadapter As New FundCenterParentTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterParent.FctHDataTable
        Hdatatable = Hadapter.GetDataByGPath(gpath, Val(Session("planyear")))

        Dim MyNode As WebTreeViewNode
        MyNode = New WebTreeViewNode()
        For Each row As FundCenterParent.FctHRow In Hdatatable


            MyNode.Text = row.Description
            MyNode.Value = row.FundCenter_FundCenterCode

            cnode.Nodes.Add(MyNode)
        Next


        If Len(gpath) >= 10 Then
            Exit Sub
        End If

        Dim hadap2 As New FundCenterParentTableAdapters.UserLikeGpathTableAdapter
        Dim hdt2 As New FundCenterParent.UserLikeGpathDataTable
        Dim sql As String = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")

        Dim pathadd As String = "__"
        'For i = 1 To 4
        sql = ""
        Dim fullpath As String = gpath & pathadd
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " AND grouppath like '" & fullpath & "' "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND Fcth.PlanYear = " & Val(Session("PlanYear"))
        hadap2.GetDataByFilter(hdt2, sql)

        For Each row As FundCenterParent.UserLikeGpathRow In hdt2
            If Len(row.grouppath) <= 10 Then
                PlotChild(row.grouppath, MyNode, level + 1)
            End If

        Next

    End Sub

    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click
        GenerateValues()

        If TabContainer1.ActiveTab.ID = TabPanel1.ID Then
            Session.Remove("search_fctr")
            If WebCombo1.Value <> "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo2.Value, Session("users"), Val(PlanYearsTxt.Text)))
            ElseIf WebCombo1.Value <> "" And WebCombo2.Value = "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users"), Val(PlanYearsTxt.Text)))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo1.Value, WebCombo1.Value, Session("users")))
            ElseIf WebCombo1.Value = "" And WebCombo2.Value <> "" Then
                Session.Add("search_fctr", FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users"), Val(PlanYearsTxt.Text)))
                'Response.Write(FctrClass.GetFromToFundCenter(WebCombo2.Value, WebCombo2.Value, Session("users")))
            Else
                Session.Add("search_fctr", Session("prefilter"))
            End If

        ElseIf TabContainer1.ActiveTab.ID = TabPanel2.ID Then
            Session.Remove("search_fctr")
            If WebCombo3.Value = "" Then
                Session.Add("search_fctr", Session("prefilter"))
            Else
                Session.Add("search_fctr", FctrClass.GetSubFundCenter(WebCombo3.Value, Session("users"), Val(PlanYearsTxt.Text), Session("prefilter")))
            End If

        End If
        Session.Remove("Search")
        Session.Add("Search", "true")
        CheckExistData()
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()

    End Sub

    Sub GenerateValues()

        If hdf1.Value.Length = 0 And hdf3.Value.Length = 0 And hdf2.Value.Length = 0 Then
            Session("Search") = "false"
        End If
        Dim Numx As Array = hdf1.Value.Split(",")
        Dim Numx2 As Array = hdf3.Value.Split(",")
        Dim Numx3 As Array = hdf2.Value.Split(",")
        Try


            For i = 0 To Numx.Length - 1
                ms8.Items.FindByValue(Numx(i).ToString).Selected = True
            Next
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try


        Try
            If Numx2.Length > 1 Then

                For j = 0 To Numx2.Length - 1
                    ListBox1.Items.FindByValue(Numx2(j).ToString).Selected = True
                Next
            ElseIf Numx2.Length = 1 Then
                If Numx2(0).ToString <> " " Then
                    ListBox1.Items.FindByValue(Numx2(0).ToString).Selected = True
                End If

            End If
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        Try
            For k = 0 To Numx3.Length - 1

                ListBox2.Items.FindByValue(Numx3(k).ToString).Selected = True
            Next
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

    End Sub


    'Protected Sub coppy_btn_Click(sender As Object, e As ImageClickEventArgs) Handles coppy_btn.Click

    '    Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

    '    Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

    '    For Each keyValue As String In checkedRows

    '        adapter.CoppyRow(keyValue)

    '    Next keyValue

    '    WebGrid1.ClearCachedDataSource()
    '    WebGrid1.RebindDataSource()

    'End Sub

    'Protected Sub delete_btn_Click(sender As Object, e As ImageClickEventArgs) Handles delete_btn.Click

    '    Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

    '    Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

    '    For Each keyValue As String In checkedRows

    '        adapter.DeleteRow(keyValue)

    '    Next keyValue



    '    WebGrid1.ClearCachedDataSource()
    '    WebGrid1.RebindDataSource()

    'End Sub

    Protected Sub WebGrid1_InitializePostBack(ByVal sender As Object, ByVal e As ISNet.WebUI.WebGrid.PostbackEventArgs)
        If e.Action = PostBackAction.Custom Then
            Dim ActionType As String = TryCast(Request("type"), String)
            If ActionType = "1" Then
                Dim checkedRows As ArrayList = WebGrid1.RootTable.GetCheckedRows()

                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter

                For Each keyValue As String In checkedRows

                    adapter.CoppyRow(keyValue)

                Next keyValue
            Else
                Dim adapter As New fundCenterTableAdapters.BudgetDetailsTableAdapter
                Dim adapter2 As New fundCenterTableAdapters.AttachmentsTableAdapter
                For Each keyValue As String In WebGrid1.RootTable.GetCheckedRows()
                    adapter2.DeleteAttach(keyValue)
                    adapter.DeleteRow(keyValue)

                Next keyValue
            End If

            WebGrid1.ClientAction.Refresh()
        End If

    End Sub

    Protected Sub WebCombo1_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo1.InitializeDataSource

        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt



        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub WebCombo2_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo2.InitializeDataSource
        'If Session("Versions") > 1 Then
        'ds = PublicFunction.GetChild2(Session("users"))
        'ds.Tables(0).DefaultView.Sort = "FundCenterCode ASC"
        'e.DataSource = ds
        Dim adap As New BasicDataTableAdapters.FCTR_Child2TableAdapter
        Dim dt As New BasicData.FCTR_Child2DataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FundCenters.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += " and FundCenterHierarchies.PlanYear = " & Val(Session("PlanYear")) & " "
        sql += "ORDER BY FundCenterCode ASC"
        adap.GetDataByFilter(dt, sql)
        dt.Rows.Add("", "ทุกรายการ", "1", "0")
        dt.DefaultView.Sort = "FundCenterCode"
        e.DataSource = dt


        'Else
        'Dim adap As New BasicDataTableAdapters.FCTR_ChildTableAdapter
        'Dim dt As New BasicData.FCTR_ChildDataTable
        'dt = adap.GetOwnData(Session("FCTR"))
        'e.DataSource = dt
        'End If
    End Sub

    Protected Sub ImageButton1_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton1.Click
        GenerateValues()
        Dim numbers As Decimal
        Dim moduloset As Decimal
        Dim numberset As Decimal
        Dim currentmodulo As Decimal
        Dim numberround As Decimal
        Dim currentpos As Decimal = 8
        Dim x As Decimal() = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}

        Dim adapter As New SplitBudgetDSTableAdapters.Budget12TableAdapter

        For Each srt In WebGrid1.RootTable.GetCheckedRows()
            Dim row As WebGridRow = Me.WebGrid1.RootTable.Rows.GetRowByKeyValue(srt)

            If lockhash(row.Cells(1).Value.ToString.Trim) = True Then
                Continue For
            End If

            numbers = row.Cells(8).Value

            For j = 8 To 19
                numberset = numbers \ 12
                numberround = Math.Ceiling(numberset / 10) * 10

                currentmodulo = numbers Mod 12

                Dim currentnumber = numbers / 12

                moduloset += (currentnumber - numberset) + Math.Abs(numberround - numberset)
            Next
            'Dim numberset2 = numbers \ 12

            'If numberset2 = 8 Then
            '    adapter.UpdateBudget122(10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, Now(), Session("users"), Val(srt.ToString))
            'ElseIf numberset2 = 16 Then
            '    adapter.UpdateBudget122(20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, Now(), Session("users"), Val(srt.ToString))
            'ElseIf numberset2 = 25 Then
            '    adapter.UpdateBudget122(30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 0, 0, Now(), Session("users"), Val(srt.ToString))
            'ElseIf numberset2 = 33 Then
            '    adapter.UpdateBudget122(30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 0, 0, Now(), Session("users"), Val(srt.ToString))
            'ElseIf numberset2 = 42 Then
            '    adapter.UpdateBudget122(40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 60, Now(), Session("users"), Val(srt.ToString))
            If numberset Mod 10 <> 0 Then
                Dim nummonth(12) As Decimal
                Dim numceil = Math.Ceiling(((numbers / 12) / 10)) * 10
                Dim numremain As Decimal = numbers
                For i = 0 To 11
                    If i = 11 Then
                        nummonth(i) = numremain
                    End If
                    If numremain = 0 Then
                        nummonth(i) = 0
                    Else
                        If numremain <= numceil Then
                            nummonth(i) = numremain
                            numremain = 0
                        Else
                            nummonth(i) = numceil
                            numremain -= numceil
                        End If
                    End If
                    adapter.UpdateBudget122(nummonth(0), nummonth(1), nummonth(2), nummonth(3), nummonth(4), nummonth(5), nummonth(6), nummonth(7), nummonth(8), nummonth(9), nummonth(10), nummonth(11), Now(), Session("users"), Val(srt.ToString))
                Next
            Else
                adapter.UpdateBudget122(numberround, numberround, numberround, numberround, numberround, numberround, numberround, numberround, numberround, numberround, numberround, (numbers - (numberround * 11)), Now(), Session("users"), Val(srt.ToString))
            End If

            moduloset = 0
        Next

        logger.Info("User " & Session("users") & " distribute 12 months")

        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()

    End Sub

    Protected Sub ImageButton4_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton4.Click, ImageButton5.Click
        GenerateValues()
        Dim adap As New SplitDS2TableAdapters.Budget12TableAdapter
        Dim dt As New SplitDS2.Budget12DataTable
        'adap.GetDataByFilter(dt, Session("basesql"))

        Dim numbers As Decimal

        Dim adapter As New SplitBudgetDSTableAdapters.Budget12TableAdapter

        For Each srt In WebGrid1.RootTable.GetCheckedRows()
            
            Dim fctr As String = ""
            Dim prj As String = ""
            Dim act As String = ""
            Dim cmmt As String = ""
            Dim acttype As String = ""
            Dim prod As String = ""
            Dim cmmtdetail As String = ""
            Dim row As WebGridRow = Me.WebGrid1.RootTable.Rows.GetRowByKeyValue(srt)
            Dim sql As String = Session("basesql")

            If lockhash(row.Cells(1).Value.ToString.Trim) = True Then
                Continue For
            End If

            numbers = row.Cells(8).Value
            fctr = row.Cells(1).Value
            sql += " AND Budget12.Fundcenter_FundcenterCode = '" & fctr & "' "

            If Not IsDBNull(row.Cells(2).Value) Then
                prj = row.Cells(2).Value.ToString.Trim
                If prj <> "" Then
                    sql += " AND Budget12.Project_ProjectCode = '" & row.Cells(2).Value.ToString.Trim & "' "
                Else
                    sql += " AND Budget12.Project_ProjectCode IS NULL "
                End If
            Else
                sql += " AND Budget12.Project_ProjectCode IS NULL "
            End If
            If Not IsDBNull(row.Cells(7).Value) Then
                act = row.Cells(7).Value.ToString.Trim
                If act <> "" Then
                    sql += " AND Budget12.Activity_ActivityCode = '" & row.Cells(7).Value.ToString.Trim & "' "
                Else
                    sql += " AND Budget12.Activity_ActivityCode IS NULL "
                End If
            Else
                sql += " AND Budget12.Activity_ActivityCode IS NULL "
            End If
            If Not IsDBNull(row.Cells(3).Value) Then
                cmmt = row.Cells(3).Value.ToString.Trim
                If cmmt <> "" Then
                    sql += " AND Budget12.Cmmt_CmmtCode = '" & row.Cells(3).Value.ToString.Trim & "' "
                Else
                    sql += " AND Budget12.Cmmt_CmmtCode IS NULL "
                End If
            Else
                sql += " AND Budget12.Cmmt_CmmtCode IS NULL "
            End If
            If Not IsDBNull(row.Cells(5).Value) Then
                acttype = row.Cells(5).Value.ToString.Trim
                If acttype <> "" Then
                    sql += " AND Budget12.ActivityType_ActivityTypeCode = '" & row.Cells(5).Value.ToString.Trim & "' "
                Else
                    sql += " AND Budget12.ActivityType_ActivityTypeCode IS NULL "
                End If
            Else
                sql += " AND Budget12.ActivityType_ActivityTypeCode IS NULL "
            End If
            If Not IsDBNull(row.Cells(4).Value) Then
                prod = row.Cells(4).Value.ToString.Trim
                If prod <> "" Then
                    sql += " AND Budget12.Product_ProductCode = '" & row.Cells(4).Value.ToString.Trim & "' "
                Else
                    sql += " AND Budget12.Product_ProductCode IS NULL "
                End If
            Else
                sql += " AND Budget12.Product_ProductCode IS NULL "
            End If
            If Not IsDBNull(row.Cells(6).Value) Then
                sql += " AND Budget12.CmmtDetail_Id = " & row.Cells(6).Value
            Else
                sql += " AND Budget12.CmmtDetail_Id IS NULL "
            End If
            'MsgBox(sql)
            adap.GetDataByFilter(dt, sql)
            If dt.Count > 0 Then
                Dim nummonth(11) As Decimal
                Dim numremain As Decimal = numbers
                For i = 0 To 11
                    Select Case i
                        Case 0
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent1) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 1
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent2) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 2
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent3) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 3
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent4) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 4
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent5) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 5
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent6) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 6
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent7) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 7
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent8) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 8
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent9) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 9
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent10) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 10
                            nummonth(i) = Math.Ceiling(((numbers * dt.Item(0).percent11) / 100) / 10) * 10
                            numremain -= nummonth(i)
                        Case 11
                            nummonth(i) = numremain
                    End Select
                Next
                adapter.UpdateBudget122(nummonth(0), nummonth(1), nummonth(2), nummonth(3), nummonth(4), nummonth(5), nummonth(6), nummonth(7), nummonth(8), nummonth(9), nummonth(10), nummonth(11), Now(), Session("users"), Val(srt.ToString))
            End If

        Next

        If basemode = 1 Then
            logger.Info("User " & Session("users") & " distribute BASEBUDGET months")
        Else
            logger.Info("User " & Session("users") & " distribute BASECASHFLOW months")
        End If

        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()

    End Sub

    Sub GenData()
        Dim adapter12 As New SplitData2TableAdapters.Budget12TableAdapter
        Dim data As New SplitData2.Budget12DataTable
        Dim data2 As New SplitData2.Budget12DataTable
        Dim checksql = ""
        checksql = "select *,0 As Amount from budget12 "
        checksql += " Where PlanYear = '" & Val(PlanYearsTxt.Text) & "' AND Version = '" & VersionTxt.Text & "' "
        Dim fctr As String = ""
        fctr = Session("search_fctr")
        Dim prefil As String = ""
        prefil = Session("prefilter")
        If fctr <> "" Then
            checksql += " AND Budget12.FundCenter_FundCenterCode IN (" & fctr & ") "
        Else
            checksql += " AND Budget12.FundCenter_FundCenterCode IN (" & prefil & ") "
        End If
        If hdf1.Value.ToString <> "" Then
            checksql += " AND Budget12.Project_ProjectCode IN ("
            Dim Numx As Array = hdf1.Value.Split(",")
            For i = 0 To Numx.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx(i).ToString & "'"
            Next
            checksql += ") "
        End If

        If hdf3.Value.ToString <> "" Then
            checksql += " AND Budget12.Cmmt_CmmtCode  IN ("
            Dim Numx2 As Array = hdf3.Value.Split(",")
            For i = 0 To Numx2.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx2(i).ToString & "'"
            Next
            checksql += ") "
        End If
        If hdf2.Value.ToString <> "" Then
            checksql += " AND  Budget12.Activity_ActivityCode IN ("
            Dim Numx3 As Array = hdf2.Value.Split(",")
            For i = 0 To Numx3.Length - 1
                If i <> 0 Then
                    checksql += ","
                End If
                checksql += "'" & Numx3(i).ToString & "'"
            Next
            checksql += ") "
        End If

        checksql += " Order By FundCenter_FundCenterCode "
        adapter12.GetDataByFilter(data2, checksql)

        WebGrid1.DataSource = data2

    End Sub
    Protected Sub ImageButton2_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton2.Click
        GenerateValues()
        Dim numbers As Decimal
        Dim moduloset As Decimal
        Dim numberset As Decimal
        Dim currentmodulo As Decimal
        Dim numberround As Decimal
        Dim currentpos As Decimal = 8
        Dim modtrimas1, modtrimas2, modtrimas3, modtrimas4 As Decimal
        Dim x As Decimal() = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}

        Dim adapter As New SplitBudgetDSTableAdapters.Budget12TableAdapter


        For Each srt In WebGrid1.RootTable.GetCheckedRows()
            Dim row As WebGridRow = Me.WebGrid1.RootTable.Rows.GetRowByKeyValue(srt)
            numbers = row.Cells(8).Value

            If lockhash(row.Cells(1).Value.ToString.Trim) = True Then
                Continue For
            End If

            For j = 0 To 3
                numberset = numbers \ 4
                modtrimas1 = Math.Ceiling(numberset / 10) * 10

                currentmodulo = numbers Mod 4

                Dim currentnumber = numbers / 4

                moduloset += (currentnumber - numberset) + Math.Abs(modtrimas1 - numberset)





            Next
            Dim numberset2 = numbers \ 4
            If numberset2 = 7 Then
                adapter.UpdateBudget122(0, 0, 8, 0, 0, 8, 0, 0, 8, 0, 0, 6, Now(), Session("users"), Val(srt.ToString))
            ElseIf numberset2 = 25 Then
                adapter.UpdateBudget122(0, 0, 30, 0, 0, 30, 0, 0, 30, 0, 0, 10, Now(), Session("users"), Val(srt.ToString))
            ElseIf numberset2 = 75 Then
                adapter.UpdateBudget122(0, 0, 80, 0, 0, 80, 0, 0, 80, 0, 0, 60, Now(), Session("users"), Val(srt.ToString))
            ElseIf numberset2 = 125 Then
                adapter.UpdateBudget122(0, 0, 130, 0, 0, 130, 0, 0, 130, 0, 0, 110, Now(), Session("users"), Val(srt.ToString))
            Else
                adapter.UpdateBudget122(0, 0, modtrimas1, 0, 0, modtrimas1, 0, 0, modtrimas1, 0, 0, numbers - (modtrimas1 * 3), Now(), Session("users"), Val(srt.ToString))
            End If

            moduloset = 0


        Next

        logger.Info("User " & Session("users") & " distribute quarterly")

        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()

    End Sub

    Protected Sub ImageButton3_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton3.Click
        GenerateValues()
        Dim texter As String = ""
        For Each srt In WebGrid1.RootTable.GetCheckedRows()
            texter = texter & srt.ToString & ";"
        Next

        logger.Info("User " & Session("users") & " distribute specific month")

        ScriptText = "<script> popupkrajay3('" & texter & "');</script>"
    End Sub

    Protected Sub SaveBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SaveBtn.Click
        WebGrid1.ClearCachedDataSource()
        WebGrid1.RebindDataSource()
    End Sub

    Protected Sub WebCombo3_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles WebCombo3.InitializeDataSource

        Dim adap As New FundCenterParentTableAdapters.SelectorTableAdapter
        Dim dt As New FundCenterParent.SelectorDataTable
        Dim dt2 As New FundCenterParent.SelectorDataTable
        Dim sql = ""
        Dim prefil As String = ""
        prefil = Session("prefilter")
        sql += " WHERE 1 = 1 "
        sql += " and USERNAME = '" & Session("users") & "' AND fctr_view.PlanYear = " & Val(Session("PlanYear")) & " AND FctH.PlanYear = " & Val(Session("PlanYear"))
        If prefil <> "" Then
            sql += " AND fctr_view.FundCenterCode IN (" & prefil & ") "
        End If
        sql += "ORDER BY Grouppath"
        adap.GetDataByFilter(dt2, sql)
        dt.Rows.Add("ทุกรายการ", "0", 0, "0", Val(Session("PlanYear")), "ทุกรายการ")
        dt.Merge(dt2)
        'dt.DefaultView.Sort = "FundCenter_FundCenterCode"
        e.DataSource = dt



    End Sub
End Class
